import asyncio
import random
from typing import List, Callable, Any

async def async_task(task_id: int) -> str:
    """模拟一个异步任务"""
    print(f"开始执行任务 {task_id}")
    await asyncio.sleep(random.uniform(0.5, 2))  # 模拟任务执行时间
    print(f"任务 {task_id} 执行完成")
    return f"任务 {task_id} 的结果"

async def batch_executor(tasks: List[Callable[[], Any]], batch_size: int) -> List[Any]:
    """批量执行任务的协程"""
    results = []
    for i in range(0, len(tasks), batch_size):
        batch = tasks[i:i+batch_size]
        batch_results = await asyncio.gather(*[task() for task in batch])
        results.extend(batch_results)
        print(f"完成批次 {i//batch_size + 1}")
    return results

async def main():
    # 创建一系列任务
    num_tasks = 20
    tasks = [lambda i=i: async_task(i) for i in range(num_tasks)]
    print(tasks[0])
    # 设置批次大小
    batch_size = 5

    # 批量执行任务
    results = await batch_executor(tasks, batch_size)

    # 打印结果
    print("\n所有任务的结果:")
    for result in results:
        print(result)

if __name__ == "__main__":
    asyncio.run(main())
